package com.tuanbiao.ui.upload;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.abiao.lib_utils.ViewUtils;
import com.hzjq.data.base.UploadBlastService;
import com.hzjq.data.entity.BlastDetailEntity;
import com.hzjq.data.entity.BlastEntity;
import com.hzjq.data.hzjq.entity.CapRecordEntity;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.sort.comparable.CapUidComparable;
import com.tuanbiao.R;
import com.tuanbiao.base.mvp.BasePresenterActivity;
import com.tuanbiao.controllers.UploadDataController;
import com.tuanbiao.data.entity.UploadServiceBean;
import com.tuanbiao.databinding.ActivityUploadDataDetailsBinding;
import com.tuanbiao.dialog.UploadErrorDialog;
import com.tuanbiao.dialog.WaitDialog;
import com.tuanbiao.events.BlastDetailsEvent;
import com.tuanbiao.keyevent.KeyEventHelper;
import com.tuanbiao.keyevent.listener.OnKeyDownListener;
import com.tuanbiao.models.UploadDataModel;
import com.tuanbiao.presenter.UploadDataDetailsPresenter;
import com.tuanbiao.ui.log.LogOperateActivity;
import com.tuanbiao.utils.ClickUtil;
import com.tuanbiao.utils.LibCollections;
import com.tuanbiao.utils.ThreadMainTaskManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.disposables.Disposable;

public class UploadDataDetailsActivity extends BasePresenterActivity<UploadDataDetailsPresenter, ActivityUploadDataDetailsBinding> implements UploadDataController.DetailsView {
    private UploadDataDetailsAdapter uploadDataDetailsAdapter;
    private UploadDataDetailsServiceAdapter uploadDataDetailsServiceAdapter;
    private WaitDialog.Builder waitDialogBuilder;
    private Disposable sortDisposable;

    public static void start(Context context) {
        Intent starter = new Intent(context, UploadDataDetailsActivity.class);
        context.startActivity(starter);
    }

    public static Intent createIntent(Context context) {
        return new Intent(context, UploadDataDetailsActivity.class);
    }

    @Override
    protected ActivityUploadDataDetailsBinding getBindingView() {
        return ActivityUploadDataDetailsBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        binding.ivToolbarBack.setOnClickListener(getBackListener());
        binding.rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        uploadDataDetailsAdapter = new UploadDataDetailsAdapter();
        binding.rvContent.setAdapter(uploadDataDetailsAdapter);
        binding.rvService.setLayoutManager(new LinearLayoutManager(getActivity()));
        uploadDataDetailsServiceAdapter = new UploadDataDetailsServiceAdapter();
        binding.rvService.setAdapter(uploadDataDetailsServiceAdapter);
        binding.tvLog.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            mPresenter.startOperateLog();
        });
        binding.tvCommit.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            showErrorUploadSelectDialog();
        });
    }

    private void showErrorUploadSelectDialog(){
        if(mPresenter.getErrorCount() > 0) {
            UploadErrorDialog.show(getActivity(), "当前记录中包含"+mPresenter.getErrorCount()+"发异常雷管信息，是否需要全部上传？",
                    new UploadErrorDialog.OnUploadMenuItemClickListener() {
                        @Override
                        public void onUploadClick(boolean isAll) {
                            mPresenter.update(isAll);
                        }
                    });
        } else  {
            mPresenter.update(true);
        }
    }

    @Override
    protected UploadDataDetailsPresenter createPresenter() {
        return new UploadDataDetailsPresenter(new UploadDataModel(), this);
    }

    @Override
    public void setItems(List<CapRecordEntity> caps) {
        if (LibCollections.isEmpty(caps)) {
            uploadDataDetailsAdapter.setEmptyView(ViewUtils.layoutId2View(R.layout.include_no_data));
        }
        binding.tvDetonatorCount.setText(getString(R.string.upload_data_details_detonator_count, LibCollections.size(caps)));
        sortDisposable = ThreadMainTaskManager.startTask(new ThreadMainTaskManager.OnThreadMainTaskCallback<List<CapRecordEntity>>() {

            @Override
            public List<CapRecordEntity> doThreadTask() {
                Collections.sort(caps, new CapUidComparable());
                return caps;
            }

            @Override
            public void doMainTask(List<CapRecordEntity> capRecordEntities) {
                releaseSortDisposable();
                uploadDataDetailsAdapter.setNewInstance(capRecordEntities);
            }
        });

    }

    private void releaseSortDisposable(){
        if(sortDisposable != null && !sortDisposable.isDisposed()){
            sortDisposable.dispose();
        }
    }

    @Override
    public void startLog(BlastDetailEntity entity) {
        EventBus.getDefault().postSticky(new BlastDetailsEvent(entity));
        LogOperateActivity.start(getActivity());
    }

    @Override
    public void showLoading() {
        if (null == waitDialogBuilder) {
            waitDialogBuilder = new WaitDialog.Builder(getActivity()).setMessage("正在上传");
        }
        waitDialogBuilder.show();
    }

    @Override
    public void hideLoading() {
        if (null != waitDialogBuilder && waitDialogBuilder.isShowing()) {
            waitDialogBuilder.dismiss();
        }
    }

    @Override
    public void showDetails(BlastDetailEntity entity) {
        binding.tvContractCode.setText(getString(R.string.upload_data_details_contract_num, entity.getPm().getPmHtId()));
    }

    @Override
    public void showDetails(BlastEntity entity) {
        List<UploadServiceBean> uploadServiceBeans = new ArrayList<>();
        Set<Map.Entry<UploadBlastService, Boolean>> entries = entity.getUploadedServices().entrySet();
        for (Map.Entry<UploadBlastService, Boolean> entry : entries) {
            uploadServiceBeans.add(new UploadServiceBean(entry.getValue(), entry.getKey()));
        }
        uploadDataDetailsServiceAdapter.setNewInstance(uploadServiceBeans);
        binding.tvCommit.setEnabled(entity.getUploadStatus() != 1);
        binding.tvBlastTime.setText(getString(R.string.upload_data_details_blast_time, entity.getBlastTime()));
        binding.tvLongitude.setText(getString(R.string.upload_data_details_longitude, entity.getLon()));
        binding.tvLatitude.setText(getString(R.string.upload_data_details_latitude, entity.getLat()));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        KeyEventHelper.getInstance().checkUploadDataDetailsKeyDown(keyCode, new OnKeyDownListener() {
            @Override
            public void onSuccess() {
                if (binding.tvLog.getVisibility() == View.VISIBLE)
                    binding.tvLog.setVisibility(View.GONE);
                else binding.tvLog.setVisibility(View.VISIBLE);
            }
        });

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mPresenter.isChange()) {
            releaseSortDisposable();
            setResult(RESULT_OK);
            finish();
        } else {
            super.onBackPressed();
        }
    }
}